import React, { Component } from 'react'
import { connect, ConnectedProps } from "react-redux";
import { RouteComponentProps, withRouter } from "react-router-dom";
import DataCategory from "../../../../../types/DataCategory";
import { Button, Input, message, Spin, Table } from "antd";
import { getRes } from "../../../../../configFile";
import { listDataCategory, queryCategoryAmount, searchCategory } from "../../../../../requests/DataCategory";
import ButtonGroup from "antd/lib/button/button-group";
import { RootState } from "../../../../../reducers";
import { deleteDataCategoryModal } from "./DeleteDataCategoryModal";

// @ts-ignore
interface PropsFromRedux extends ConnectedProps<typeof connector>, RouteComponentProps {
}

interface IState {
    DataCategorySource: Array<DataCategory & { key: number }>       //显示信息
    amount: number                                                          //总共条目
    offset: number                                                          //偏移量
    limit: number                                                           //条数
    isLoading: boolean                                                       //是否加载中
    modifyModalVisible: boolean,                                             //编辑的模态框是否为显示状态
    isSearch: boolean
}

const { Search } = Input;

class ModifyDataCategoryList extends Component<PropsFromRedux, IState> {
    constructor(props: PropsFromRedux) {
        super(props)
        this.state = {
            DataCategorySource: [],
            amount: 0,
            offset: 0,
            limit: 10,
            isSearch: false,
            isLoading: true,
            modifyModalVisible: false
        }
    }

    //删除数据类型
    deleteDataCategory = (dataCategoryID: number, dataCategoryName: string, refresh: () => void) => {
        deleteDataCategoryModal(dataCategoryID, dataCategoryName, refresh);
    }

    //获取数据类型
    getDataCategory = async () => {
        console.log("分页", this.state)
        try {
            this.setState({
                ...this.state,
                isLoading: true
            })
            const amountRes = getRes(await queryCategoryAmount())
            const res = getRes(await listDataCategory(this.state.offset, this.state.limit))
            if (res.isSuccessful && amountRes.isSuccessful) {
                this.setState({
                    DataCategorySource: res.data.map((item: DataCategory) => Object.assign({}, item, { key: item.dataCategoryID })),
                    amount: amountRes.data
                })
            } else {
                message.error("查询失败")
            }

        } catch (error) {
            message.error(error.toString())
        } finally {
            this.setState({
                ...this.state,
                isLoading: false
            })
        }
    }

    onSearch: (values: string) => void = async values => {
        if (values === '') {
            await this.getDataCategory()
        } else {
            try {
                const res = getRes(await searchCategory(values))
                if (res.isSuccessful) {
                    this.setState({ DataCategorySource: res.data, amount: res.data.length, isSearch: true })
                } else {
                    console.error(res);
                    message.error("查询失败")
                }
            } catch (err) {
                message.error(JSON.stringify(err))
            }
        }
    }

    async componentDidMount() {
        await this.getDataCategory()
    }

    columns = [{
        title: '数据类型名',
        dataIndex: 'dataCategoryName',
        key: 'dataCategoryName',
        width: 300
    },
    {
        title: '数据类型',
        dataIndex: 'dataType',
        key: 'dataType',
        width: 300,
    },
    {
        title: '操作',
        key: 'action',
        render: (record: DataCategory) => (
            <ButtonGroup>
                <Button size='middle' type='primary' onClick={() => {
                    this.props.history.push(`modifyDataCategory/${record.dataCategoryID}`)
                }}>编辑</Button>
                <Button size='middle' danger
                    onClick={this.deleteDataCategory.bind(this, record.dataCategoryID, record.dataCategoryName, this.getDataCategory)}>删除</Button>
            </ButtonGroup>
        )
    }]

    render() {
        return (
            <div>
                <Spin spinning={this.state.isLoading}>
                    <Search placeholder="搜索" onSearch={values => this.onSearch(values)} allowClear={true} enterButton />
                    <Table columns={this.columns}
                        dataSource={this.state.DataCategorySource}
                        pagination={{
                            onChange: this.state.isSearch ? undefined : (page, pageSize) => {
                                console.log("page,pageSize", page, pageSize)
                                if (!!pageSize) {
                                    this.setState({
                                        offset: (page - 1) * (pageSize),
                                        limit: (pageSize)
                                    }, () => {
                                        this.getDataCategory()
                                    })
                                } else {
                                    console.error('pageSize == undefined')
                                }
                            },
                            defaultPageSize: this.state.limit,
                            total: this.state.amount,
                            showSizeChanger: false
                        }} />
                </Spin>
            </div>
        )
    }
}

const mapStateToProps = (state: RootState) => {
    return {
        userID: state.loginReducers.userID
    }
}

const connector = connect(mapStateToProps)
export default withRouter(connector(ModifyDataCategoryList))